﻿using ADRcpLib;
using ADSioLib;
using log4net;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Threading;
using System.Windows;
using Common.Models;
using System.Reflection.Emit;
using System.Windows.Shapes;
using System.Windows.Forms;
using System.IO;

namespace VirtualWall.Machines
{
    /// <summary>
    /// 识别相机
    /// 汪虎 2022-12-07
    /// </summary>
    public class Camera
    {

        #region 相关属性
        private static readonly ILog log = LogManager.GetLogger("Camera");

        /// <summary>
        /// 进出场图片保存的根目录
        /// </summary>
        public string SavePath { get { return Environment.CurrentDirectory + "\\Snap\\Temp\\"; } }

        /// <summary>
        /// 这什么玩意儿？
        /// </summary>
        private VzClientSDK.VZLPRC_PLATE_INFO_CALLBACK m_PlateResultCB = null;

        /// <summary>
        /// 当前相机的IP
        /// </summary>
        public string IP { get; set; }

        /// <summary>
        /// 当前相机识别的车牌
        /// </summary>
        public string PlateNo { get; set; } //进场车牌号码存储变量

        /// <summary>
        /// 当前相机的连接状态
        /// </summary>
        public bool IsConnected { get; set; } //进场车牌号码存储变量

        /// <summary>
        /// 相机进出口类型
        /// </summary>
        public CameraType ChannelType { get; set; }

        public int _Number = 0;
        /// <summary>
        /// 相机编号、索引
        /// </summary>
        public int Number
        {
            get
            {
                return _Number;
            }
        }

        public int _Handle = 0;
        /// <summary>
        /// 车牌识别相机句柄
        /// </summary>
        public int Handle
        {
            get
            {
                return _Handle;
            }
        }

        /// <summary>
        /// 用于输出视频的控件的句柄
        /// </summary>
        public System.IntPtr PoctureBoxHandle { get; set; } = System.IntPtr.Zero;

        public byte _State = 0;
        /// <summary>
        /// 识别相机是否在线的状态标记
        /// </summary>
        public byte State
        {
            get
            {
                return _State;
            }
        }

        /// <summary>
        /// 抓拍视频定时器
        /// </summary>
        System.Timers.Timer time_video = new System.Timers.Timer(15 * 1000);

        /// <summary>
        /// LED 定时器
        /// </summary>
        System.Timers.Timer time_led = new System.Timers.Timer(30 * 1000);

        /// <summary>
        /// 相机状态定跟踪定时器
        /// </summary>
        DispatcherTimer connStatTimer = new DispatcherTimer();

        public delegate void LprResult(int index, Camera sneder);

        public event LprResult OnResult;

        public event LprResult OnPlay;
        #endregion


        #region 车牌识别相机

        /// <summary>
        /// 初始化加载拍照识别相机
        /// </summary>
        /// <returns></returns>
        public Camera(CameraType channelType, int number, string cameraIP, string cameraUser, string cameraPwd, ushort cameraPort = 80)
        {
            IP = cameraIP;
            _Number = number;
            ChannelType = channelType;

            //连接相机
            InitCamera(cameraIP, cameraPort, cameraUser, cameraPwd);

            if (Handle != 0)
            {
                ////获取车牌信息
                //m_PlateResultCB = new VzClientSDK.VZLPRC_PLATE_INFO_CALLBACK(OnPlateInResult);
                //VzClientSDK.VzLPRClient_SetPlateInfoCallBack(Handle, m_PlateResultCB, IntPtr.Zero, 1);

                time_video.AutoReset = false;
                time_video.Elapsed += Time_video_Elapsed;

                time_led.AutoReset = false;
                time_led.Elapsed += Time_led_Elapsed;

                //启动的时候将进入场相机设置为放下状态
                var flag = VzClientSDK.VzLPRClient_SetIOOutput(_Handle, 0, 0);
                if (flag == 0)
                {
                    log.Info($"电子围栏 相机：{cameraIP} 放下栏杆：成功！");
                }
                else
                {
                    log.Info($"电子围栏 相机：{cameraIP} 放下栏杆：失败！状态：{flag}");
                }
                Thread.Sleep(500);

                //貌似是定期检测相机是否在线
                connStatTimer = new DispatcherTimer { Interval = TimeSpan.FromSeconds(10) };
                connStatTimer.Start();
                connStatTimer.Tick += (sender, args) =>
                {
                    if (Handle != 0) VzClientSDK.VzLPRClient_IsConnected(Handle, ref _State);

                    if (State == 0)
                    {
                        //再次尝试连接相机
                        InitCamera(cameraIP, cameraPort, cameraUser, cameraPwd);
                        log.Info($"检测到车牌相机：{cameraIP} 掉线");
                    }
                };
            }

        }

        /// <summary>
        /// 播放视频
        /// </summary>
        /// <returns>小于0表示失败</returns>
        public int Play()
        {
            try
            {
                if (Handle == 0 || PoctureBoxHandle == System.IntPtr.Zero) return -1;
                var state = VzClientSDK.VzLPRClient_StartRealPlay(Handle, PoctureBoxHandle);
                if (OnPlay != null)
                {
                    OnPlay(Number, this);
                }
                return state;
            }
            catch
            {
                return -1;
            }
        }


        /// <summary>
        /// 播放视频
        /// </summary>
        /// <returns>小于0表示失败</returns>
        public int Play(System.IntPtr pbHnadle)
        {
            //Task.Run(async delegate
            //{
            //    await Task.Delay(1000);
            try
            {
                PoctureBoxHandle = pbHnadle;
                return Play();
            }
            catch
            {
                return -1;
            }
            //});
        }

        /// <summary>
        /// 初始化加载拍照识别相机
        /// </summary>
        /// <returns></returns>
        private int InitCamera(string cameraIP, ushort cameraPort, string cameraUser, string cameraPwd)
        {
            if (Handle == 0)//围栏进场摄像头
            {
                _Handle = VzClientSDK.VzLPRClient_Open(cameraIP, cameraPort, cameraUser, cameraPwd);

                if (Handle != 0)
                {
                    if (ChannelType == CameraType.入口)
                    {
                        //获取车牌信息
                        m_PlateResultCB = new VzClientSDK.VZLPRC_PLATE_INFO_CALLBACK(OnPlateInResult);
                    }
                    else
                    {
                        //获取车牌信息
                        m_PlateResultCB = new VzClientSDK.VZLPRC_PLATE_INFO_CALLBACK(OnPlateOutResult);
                    }

                    VzClientSDK.VzLPRClient_SetPlateInfoCallBack(Handle, m_PlateResultCB, IntPtr.Zero, 1);
                    _State = 1;
                    IsConnected = true;
                    log.Info($"电子围栏 相机：{cameraIP} 登录：成功！");
                }
                else
                {
                    _State = 0;
                    IsConnected = false;
                    log.Info($"电子围栏 相机：{cameraIP} 登录：失败！");
                }
            }
            return _Handle;
        }

        #region 围栏识别相机的回调函数
        /// <summary>
        /// 入场摄像头识别后执行的操作，需要记录当前车牌的
        /// </summary>
        /// <param name="handle"></param>
        /// <param name="pUserData"></param>
        /// <param name="pResult"></param>
        /// <param name="uNumPlates"></param>
        /// <param name="eResultType"></param>
        /// <param name="pImgFull"></param>
        /// <param name="pImgPlateClip"></param>
        /// <returns></returns>
        private int OnPlateInResult(int handle, IntPtr pUserData, IntPtr pResult, uint uNumPlates,
        VzClientSDK.VZ_LPRC_RESULT_TYPE eResultType, IntPtr pImgFull, IntPtr pImgPlateClip)
        {
            if (eResultType != VzClientSDK.VZ_LPRC_RESULT_TYPE.VZ_LPRC_RESULT_REALTIME)
            {
                VzClientSDK.TH_PlateResult result = (VzClientSDK.TH_PlateResult)Marshal.PtrToStructure(pResult, typeof(VzClientSDK.TH_PlateResult));
                string strLicense = new string(result.license);
                strLicense = strLicense.Replace("\0", "");

                if (strLicense == "_无_") return 0;
                if (strLicense == "无牌车") return 0;

                byte[] strDecIP = new byte[32];
                VzClientSDK.VzLPRClient_GetDeviceIP(handle, ref strDecIP[0], 32);
                string strIP = Encoding.Default.GetString(strDecIP).TrimEnd('\0');

                //string tempPicPath = SavePath + strLicense + "_VirtualWall_In.jpg";

                string tempPicPath = $"{GetImgDirectory(strLicense)}{strLicense}_{DateTime.Now.ToString("yyyyMMddHHmmss")}_VirtualWall_In.jpg";

                VzClientSDK.VzLPRClient_ImageSaveToJpeg(pImgFull, tempPicPath, 100);
                PlateNo = strLicense;
                //执行闸机在车辆进入时的动作
                GoIn(handle, PlateNo);
                //仅仅作记录
                log.Info(strIP + " 检测到车牌 " + strLicense);
            }

            return 0;
        }

        /// <summary>
        /// 出场摄像头识别后执行的操作
        /// </summary>
        /// <param name="handle"></param>
        /// <param name="pUserData"></param>
        /// <param name="pResult"></param>
        /// <param name="uNumPlates"></param>
        /// <param name="eResultType"></param>
        /// <param name="pImgFull"></param>
        /// <param name="pImgPlateClip"></param>
        /// <returns></returns>
        private int OnPlateOutResult(int handle, IntPtr pUserData, IntPtr pResult, uint uNumPlates,
          VzClientSDK.VZ_LPRC_RESULT_TYPE eResultType, IntPtr pImgFull, IntPtr pImgPlateClip)
        {
            if (eResultType != VzClientSDK.VZ_LPRC_RESULT_TYPE.VZ_LPRC_RESULT_REALTIME)
            {
                VzClientSDK.TH_PlateResult result = (VzClientSDK.TH_PlateResult)Marshal.PtrToStructure(pResult, typeof(VzClientSDK.TH_PlateResult));
                string strLicense = new string(result.license);
                strLicense = strLicense.Replace("\0", "");

                if (strLicense == "_无_") return 0;
                if (strLicense == "无牌车") return 0;

                byte[] strDecIP = new byte[32];
                VzClientSDK.VzLPRClient_GetDeviceIP(handle, ref strDecIP[0], 32);
                string strIP = Encoding.Default.GetString(strDecIP).TrimEnd('\0');


                //查询本次称重记录是否存在
                Common.Models.WeighingRecordModel record = Common.Data.SQLDataAccess.GetWeighingRecord(strLicense);

                //启动录像

                //VzClientSDK.VzLPRClient_StopSaveRealData(AppContext.FlowControl.handle2);
                //Thread.Sleep(100);
                //time_video = new System.Timers.Timer();
                //time_video.Elapsed += Time_video_Elapsed;
                //string tempVideoPath = SavePath + strLicense + "_VirtualWall_Out.avi";

                string tempVideoPath =string.Empty;
                if (record!=null)
                {
                    tempVideoPath = $"{GetVideoDirectory(strLicense, record.Bh)}{strLicense}_{DateTime.Now.ToString("yyyyMMddHHmmss")}_VirtualWall_Out.avi";
                }
                else
                {
                    //tempVideoPath = $"{GetVideoDirectory(strLicense)}{strLicense}_VirtualWall_Out.avi";
                    //没有称重记录的情况下，说明这个车不是称重的，那么就不能存放到称重记录图片文件夹里。
                    //因为哪里，在每次最后称重的时候会剪切图片到当前称重记录里并且上传至
                    //云端，这样就造成了错误的上传。所以将出场图片保存到临时文件夹里，以作备案。
                    tempVideoPath = $"{SavePath}{strLicense}_{DateTime.Now.ToString("yyyyMMddHHmmss")}_VirtualWall_Out.avi";
                }


                var flag = VzClientSDK.VzLPRClient_SaveRealData(handle, tempVideoPath);

                if (handle == Handle)
                {
                    time_video.Start();
                }

               // string tempPicPath = SavePath + strLicense + "_VirtualWall_Out.jpg";
                string tempPicPath = string.Empty;
                if (record != null)
                {
                    tempPicPath = $"{GetImgDirectory(strLicense, record.Bh)}{strLicense}_{DateTime.Now.ToString("yyyyMMddHHmmss")}_VirtualWall_Out.jpg";
                    VzClientSDK.VzLPRClient_ImageSaveToJpeg(pImgFull, tempPicPath, 100);
                    Thread.Sleep(500);
                    //将图片重新上传一边到云端，此时已经有了车辆出电子围栏时候的照片了。
                    //2023-03-22 因为上传图片由之前直接上传到九象平台，改成了上传到阿里，所以影响了现有的电子围栏的图片上传逻辑，故此将底下上传图片的逻辑暂时注释不传
                   // Common.SyncData.Instal.Up_Image_Data(record.Bh, strLicense);
                }
                else
                {
                    //tempPicPath = $"{GetImgDirectory(strLicense)}{strLicense}_VirtualWall_Out.jpg";
                    //没有称重记录的情况下，说明这个车不是称重的，那么就不能存放到称重记录图片文件夹里。
                    //因为哪里，在每次最后称重的时候会剪切图片到当前称重记录里并且上传至
                    //云端，这样就造成了错误的上传。所以将出场图片保存到临时文件夹里，以作备案。
                    tempPicPath = $"{SavePath}{strLicense}_{DateTime.Now.ToString("yyyyMMddHHmmss")}_VirtualWall_Out.jpg";

                    VzClientSDK.VzLPRClient_ImageSaveToJpeg(pImgFull, tempPicPath, 100);
                }

                PlateNo = strLicense;
                AppContext.CurrentOutPlate = PlateNo;
                //执行闸机在车辆出场时的动作
                GoOut(handle, PlateNo);
                log.Info(strIP + " 检测到车牌 " + strLicense);
            }

            return 0;
        }

        /// <summary>
        /// 车辆进入的时候要执行的动作
        /// </summary>
        /// <param name="pateNo">车牌号</param>
        public void GoIn(int handle, string pateNo)
        {
            var line1 = $"{pateNo}";
            var line2 = "欢迎光临";
            var line3 = "减速慢行";
            var line4 = $"{DateTime.Now.ToString("yyyy年MM月dd日 HH:mm:ss")}";

            //打开485串口
            VzClientSDK.VZDEV_SERIAL_RECV_DATA_CALLBACK serial_recv_ = null;
            //serial_handle1 = VzClientSDK.VzLPRClient_SerialStart(handle1, 0, serial_recv_, IntPtr.Zero);
            var serial_handle1 = VzClientSDK.VzLPRClient_SerialStart(handle, 0, serial_recv_, IntPtr.Zero);
            if (serial_handle1 == 0)
            {
                log.Info("相机1的485串口1打开失败!");
            }
            bool flag = true;
            //因为称重没有准备就绪的时候 会播报下面的内容所以删除了 播报参数，
            var mess = $"";
            //如果有，查询车牌白名单
            if (ConfigurationManager.AppSettings["VWWhiteListeEnable"] == "1")
            {
                var carInfo = SQLDataAccess.LoadCar(pateNo);
                if (carInfo == null)
                {
                    //LED 文本
                    line2 = $"未经授权";
                    line3 = $"禁止通行";

                    log.Debug("识别到非白名单中的车牌:" + pateNo);
                    mess = $"{pateNo}未授权";
                    flag = false;
                }
                else if (carInfo.enddate > DateTime.Now)//超过有效期限
                {
                    //LED 文本
                    line2 = $"已过期";
                    line3 = $"禁止通行";

                    log.Debug("识别到超过有效期限的车牌:" + pateNo);
                    mess = $"{pateNo}已过期";
                    flag = false;
                }
            }

            if (OnResult != null)
            {
                OnResult(Number, this);
            }

            ////发送语音数据
            ////TTSHelper.TTS(mess);
            ////发送LED显示数据
            //SendMsgToCameraLED(serial_handle1, "衡七管家", "全程抓拍", "自动称重", "缓慢上磅", mess, "g");
            LEDHandle.SendMsgToCameraLED(serial_handle1, line1, line2, line3, line4, mess, "g");

            //启用定时刷新LED为默认文本的显示的定时器，在30秒后会自动刷新称默认文本显示
            time_led.Start();

            if (flag)
            {

                //检查是否多次被拍摄而抬杆但没有进去的，这个时候就检查是否未完成的停车记录，
                ////如果有则表明他触发了入场抬杆，但没有进去的情况。这个时候
                //就不再新增数据，而是继续使用未完成的那条停车记录。
                var noFinish = SQLDataAccess.CarFeeNoFinish(pateNo);
                if (noFinish == null)//表明需要新增入场停车记录
                {
                    SQLDataAccess.SaveCarFee(new Models.CarFeeModel() { PlateNo = PlateNo, InDate = DateTime.Now });
                }


                if (ConfigurationManager.AppSettings["VWOpenBarrier"] == "1")
                {
                    //抬杆
                    log.Info("0x08F0 第一个 开：" + VzClientSDK.VzLPRClient_SetIOOutput(handle, 0, 1));
                    Thread.Sleep(500);
                    log.Info("0x08F0 第一个 关：" + VzClientSDK.VzLPRClient_SetIOOutput(handle, 0, 0));
                    Thread.Sleep(500);
                }
            }

        }

        /// <summary>
        /// 车辆出去的时候要执行的动作
        /// </summary>
        /// <param name="pateNo">车牌号</param>
        public void GoOut(int handle, string pateNo)
        {
            var mess = string.Empty;
            var line1 = $"{pateNo}";
            var line2 = "一路顺风";
            var line3 = "减速慢行";
            var line4 = $"{DateTime.Now.ToString("yyyy年MM月dd日 HH:mm:ss")}";

            //进行数据库查询，检查称重记录是否完整、费用是否缴清（暂不做处理）
            //查询称重记录是否完整
            //var WH_Record = SQLDataAccess.LoadWeighingRecord(pateNo, false);
            //var WH_Record = SQLDataAccess.GetWeighingRecord(pateNo);
            var noFinish = SQLDataAccess.CarFeeNoFinish(pateNo);
            var flag = ConfigurationManager.AppSettings["EnableWeighFinish"];

            Common.Models.WeighingRecordModel WH_Record = Common.Data.SQLDataAccess.GetWeighingRecord(pateNo);
            //打开485串口
            VzClientSDK.VZDEV_SERIAL_RECV_DATA_CALLBACK serial_recv_ = null;
            var serial_handle = VzClientSDK.VzLPRClient_SerialStart(handle, 0, serial_recv_, IntPtr.Zero);
            if (serial_handle == 0)
            {
                log.Info($"相机：{IP} 的485串口1打开失败!");
            }

            /* if (WH_Record != null && flag == "1")*///如果存在未完成的记录，并且参数设置里设置了是要验证称重记录完整性的。需要1、语音提醒。2、闸道不放行
            if (WH_Record == null || !WH_Record.IsFinish && flag == "1")
            {
                //LED 文本
                line2 = $"未称重完成";
                line3 = $"请返回称重";
                line4 = $"禁止通行";
                //1、语音提示
                //mess = $"{m_PlateNo} 禁止通行";
                mess = $"{pateNo}禁止通行";
                //TTSHelper.TTS(mess);
                log.Info($"存在未完成的称重记录：{mess}");
            }
            //else if (WH_Record.IsPay == 0)
            //{//存在未支付的称重订单
            //    mess = $"{pateNo}禁止通行";
            //    log.Info($"存在未支付的称重费用：{mess}");
            //}
            //else if (noFinish.IsPay == 0)
            //{//存在未支付的停车订单
            //    mess = $"{pateNo}禁止通行";
            //    log.Info($"存在未支付的停车费用：{mess}");
            //}
            else
            {
                var VWStorageOverflow = ConfigurationManager.AppSettings["VWStorageOverflow"];
                //是否启用超出授信车辆禁止出场 1、启用 2、不启用。同时判断称重磅单里是否选择了客户，如果没有，则不进行授信判断
                if (VWStorageOverflow == "1" && !string.IsNullOrEmpty(WH_Record.Kh))
                {
                    //检查是否超过授信额度，超过就不放行
                    var record = Common.Data.SQLDataAccess.GetBalancePay(WH_Record.Kh);
                    if (record != null && record.Credit <= 0)
                    {
                        mess = $"{pateNo}禁止通行";
                        log.Info($"超过授信额度：{record.Credit}。{mess}");
                    }
                }
                else      
                {
                    if (noFinish != null)//车辆已经出场了，需要更新出场时间和出场状态
                    {
                        noFinish.ISFinish = true;
                        noFinish.OutDate = DateTime.Now;
                        SQLDataAccess.UpdateCarFee(noFinish);
                    }
                    AppContext.CurrentOutPlate = string.Empty;//清空离场车牌号码

                    if (ConfigurationManager.AppSettings["VWOpenBarrier"] == "1")
                    {
                        log.Info("0x08F0 第二个 开：" + VzClientSDK.VzLPRClient_SetIOOutput(handle, 0, 1));
                        Thread.Sleep(500);
                        log.Info("0x08F0 第二个 关：" + VzClientSDK.VzLPRClient_SetIOOutput(handle, 0, 0));
                        Thread.Sleep(500);
                    }

                    mess = $"{pateNo}一路顺风";
                    log.Info(mess);

                    //上传第三方平台 - > 电子围栏的数据
                    if (WH_Record != null && !Common.Platform.PlatformManager.Instance.IsDefault)
                    {
                        var channel = string.IsNullOrEmpty(WH_Record.Weigh2Name) ? "9QRX0" : WH_Record.Weigh2Name.StartsWith("9QRX0") ? WH_Record.Weigh2Name : "9QRX0";
                        Common.Platform.PlatformManager.Instance.Current.UploadVWData(WH_Record, channel, SavePath, SavePath);
                    }
                }
            }

            if (OnResult != null)
            {
                OnResult(Number, this);
            }

            //发送LED显示数据
            LEDHandle.SendMsgToCameraLED(serial_handle, line1, line2, line3, line4, mess, "g");

            //启用定时刷新LED为默认文本的显示的定时器，在30秒后会自动刷新称默认文本显示
            time_led.Start();
        }

        /// <summary>
        /// 打开栏杆
        /// </summary>
        public void OpenBarrier()
        {
            //抬杆
            log.Info("0x08F0 第一个 开：" + VzClientSDK.VzLPRClient_SetIOOutput(Handle, 0, 1));
            Thread.Sleep(500);
            log.Info("0x08F0 第一个 关：" + VzClientSDK.VzLPRClient_SetIOOutput(Handle, 0, 0));
        }

        /// <summary>
        /// 关闭栏杆
        /// </summary>
        public void CloseBarrier()
        {
            //抬杆
            log.Info("0x08F0 第一个 开：" + VzClientSDK.VzLPRClient_SetIOOutput(Handle, 0, 1));
            Thread.Sleep(500);
            log.Info("0x08F0 第一个 关：" + VzClientSDK.VzLPRClient_SetIOOutput(Handle, 0, 0));
        }

        /// <summary>
        /// 关闭视频播放，停止相机工作，释放相机资源
        /// </summary>
        public void Dispose()
        {
            try
            {
                VzClientSDK.VzLPRClient_StopRealPlay(Handle);
                VzClientSDK.VzLPRClient_Close(Handle);
            }
            catch (Exception e)
            {
                log.Info("Camera Dispose：" + e.Message);
            }
        }

        private void Time_led_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            //打开485串口
            VzClientSDK.VZDEV_SERIAL_RECV_DATA_CALLBACK serial_recv_ = null;
            var serial_handle = VzClientSDK.VzLPRClient_SerialStart(Handle, 0, serial_recv_, IntPtr.Zero);
            if (serial_handle == 0)
            {
                log.Info($"相机：{IP} 的485串口1打开失败!");
            }

            if (ChannelType == CameraType.出口)
            {
                var ttsMess = string.Empty;
                var line1 = $"称重出场";
                var line2 = "减速慢行";
                var line3 = "一车一杆";
                var line4 = $"{DateTime.Now.ToString("yyyy年MM月dd日 HH:mm:ss")}";
                //发送LED显示数据
                LEDHandle.SendMsgToCameraLED(serial_handle, line1, line2, line3, line4, ttsMess, "g");
            }
            else if (ChannelType == CameraType.入口)
            {
                var ttsMess = string.Empty;
                var line1 = $"自动识别";
                var line2 = "减速慢行";
                var line3 = "一车一杆";
                var line4 = $"{DateTime.Now.ToString("yyyy年MM月dd日 HH:mm:ss")}";
                //发送LED显示数据
                LEDHandle.SendMsgToCameraLED(serial_handle, line1, line2, line3, line4, ttsMess, "g");
            }

        }
        private void Time_video_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            try
            {
                var time = sender as System.Timers.Timer;

                if (time == null)
                {
                    return;
                }

                //停止录像
                var flag = VzClientSDK.VzLPRClient_StopSaveRealData(Handle);
                //time.Stop();

                ////执行闸机在车辆出场时的动作
                GoOut(Handle, PlateNo);//出口相机2
            }
            catch { }
        }

        #endregion

        #endregion


        private string GetImgDirectory(string ch, string bh = "")
        {
            try
            {
                var lprPath = Common.Utility.SettingsHelper.LPRSavePath;
                string basePath = $"{lprPath}\\{ch}\\";
                string root = $"{basePath}\\{bh}\\";
                if (bh == "")
                {
                    if (!Directory.Exists(basePath)) Directory.CreateDirectory(basePath);
                    return basePath;
                }
                else
                {
                    if (!Directory.Exists(root)) Directory.CreateDirectory(root);
                    return root;
                }
            }
            catch (Exception e)
            {
                log.Debug(e.Message);
                return string.Empty;
            }
        }

        private string GetVideoDirectory(string ch, string bh = "")
        {
            try
            {
                var lprPath = Common.Utility.SettingsHelper.MonitorSavePath;
                string basePath = $"{lprPath}\\{ch}\\";
                string root = $"{basePath}\\{bh}\\";
                if (bh == "")
                {
                    if (!Directory.Exists(basePath)) Directory.CreateDirectory(basePath);
                    return basePath;
                }
                else
                {
                    if (!Directory.Exists(root)) Directory.CreateDirectory(root);
                    return root;
                }
            }
            catch (Exception e)
            {
                log.Debug(e.Message);
                return string.Empty;
            }
        }

    }

    public enum CameraType
    {
        入口 = 0,
        出口 = 1
    }

}
